package com.fingard.dsp.bank.directbank.bjums01;

import com.fingard.common.utils.json.JSONUtils;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.*;

public class BJUMS01Base extends DirectBase {
    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    protected String getCharset(String p_def, String p_for) {
        return getBankConfig().getCharset(p_def, p_for);
    }

    public HashMap<String, String> getOpenid(String p_appId, String p_appSecret, String p_code) {
        HashMap<String, String> retHash = new HashMap<String, String>();

        String respCode = "";
        String respInfo = "";

        String tmpUrl = bankFront.getUrl("access_token");
        if (StringHelper.isNullOrEmpty(tmpUrl)) {
            respCode = "-1";
            respInfo = "未设置“通过code换取网页授权access_token”的地址,请检查BankFront.xml相关配置!";
        } else {
            tmpUrl = tmpUrl + "?appid=" + p_appId + "&secret=" + p_appSecret + "&code=" + p_code
                    + "&grant_type=authorization_code";
            WriteBankLogStep2(tmpUrl);

            WebRequest tmpWebRequest = new WebRequest(tmpUrl);
            String[] tmpRet = tmpWebRequest.upload(null, getCharset());
            if (tmpRet[0].length() == 0) {
                WriteBankLogStep3(tmpRet[1]);

                if (tmpRet[1].startsWith("{")) {
                    retHash = JSONUtils.json2Map(tmpRet[1]);
                    respCode = "0";
                } else {
                    respCode = "-1";
                    respInfo = tmpRet[1];
                }
            } else {
                respCode = "-1";
                respInfo = tmpRet[1];
                WriteBankLogLn(tmpRet[0] + "\r\n" + tmpRet[1]);
            }
        }

        retHash.put("RespCode", respCode);
        retHash.put("RespInfo", respInfo);

        return retHash;
    }

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime17SSSFormat.format(tmpDateNow);
    }

    public static Map<String, Object> getParam(ActSetItem actItem) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("version", "1.0");
        param.put("orgId", actItem.corpCode);
        param.put("merchId", actItem.merchantId);
        return param;
    }

    public String addSign(String head, Map msgMap, String key) {

        try {
            TreeMap tree = new TreeMap();
            tree.putAll(msgMap);

            Iterator<Map.Entry> it = tree.entrySet().iterator();
            tree = new TreeMap();
            while (it.hasNext()) {
                Map.Entry en = it.next();
                if (en.getValue() == null || "".equals(en.getValue().toString().trim())) {
                    continue;
                }
                tree.put(en.getKey(), en.getValue());
            }
            StringBuffer sf = new StringBuffer();
            if (head != null && !head.equals("")) {
                sf.append(head + "&");
            }
            it = tree.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry en = it.next();
                sf.append(en.getKey() + "=" + en.getValue()
                        + "&");
            }
            if (key != null && !key.equals("")) {
                sf.append("key=" + key + "&");
            }
            String substring = sf.substring(0, sf.length() - 1);
            WriteBankLogLn("待签名串  :" + substring);


            return md5(substring, "UTF-8").toUpperCase();
        } catch (Exception e) {
            WriteBankLogLn("获取待签名串异常[" + e + "]");
            return null;
        }

    }

    public String md5(String text, String charset) throws Exception {
        return DigestUtils.md5Hex(getContentBytes(text, charset));
    }

    private byte[] getContentBytes(String content, String charset) throws Exception {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new Exception(e);
        }
    }

    /**
     * 发送并获取返回
     */
    protected String[] sendToBank(String p_reqStr, String url) throws Exception {
        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("2.提交银行的地址：" + url);
        String charsetName = "utf-8";
        WriteBankLogStep2(p_reqStr);
        WebRequest tmpWebRequest = new WebRequest(url);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/octet-stream; charset=UTF-8");
        tmpWebRequest.setRequestProperty("connection", "keep-alive");
        byte[] tmpToWriteBytes = p_reqStr.getBytes(charsetName);
        retStr = tmpWebRequest.upload(tmpToWriteBytes, charsetName);
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
}
